﻿using UnityEngine;
using System.Collections;

public class _PlayerMove2 : MonoBehaviour {
    //how fast
    public float speed = 5f;
    private Animator anim;
    Rigidbody playerRigidbody;
    Vector3 targetDir;
    private int groundLayerIndex = -1;
    private float camRayLength = 100f;



	private CharacterController cc;

    public void Awake()
    {
        anim = GetComponent<Animator>();
        playerRigidbody = GetComponent<Rigidbody>();
        groundLayerIndex = LayerMask.GetMask("Ground");


		cc = this.GetComponent < CharacterController>();
    }
	
	// Update is called once per frame
	void FixedUpdate () 
	{

        //MouseLookRotation();
        JoyRotation();

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

		
		//按键的取值以虚拟杆中的值为优先
        if (Mathf.Abs(Joystick2.h) > 0.1f || Mathf.Abs(Joystick2.v) > 0.1f)
        {
            h = Joystick2.h;
            v = Joystick2.v;
        }
		//if (Joystick2.h!= 0 || Joystick2.v!= 0||JoystickRotation.h!=0||JoystickRotation.v!=0) {
			//camScale.enabled=false;
		//}else{
			//camScale.enabled=true;
		//}
        Move();
        Animating(h, v);
	}

    void MouseLookRotation()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo, camRayLength, groundLayerIndex))
        {
            Vector3 mousePoint = hitInfo.point;
            mousePoint.y = transform.position.y;
            transform.LookAt(mousePoint);
        }
    }

    void JoyRotation()
    {
        if (Mathf.Abs(JoystickRotation.h) > 0.3f || (Mathf.Abs(JoystickRotation.v) > 0.3f))
        {

			Vector3 needLookAt = transform.position + new Vector3(JoystickRotation.h, 0, JoystickRotation.v);
            transform.LookAt(needLookAt);
		}
	}
	
    void Move()
    {
		if (Mathf.Abs(Joystick2.h) > 0.1f || (Mathf.Abs(Joystick2.v) > 0.1f))
		{

			Vector3 targetDir = new Vector3(Joystick2.h, 0, Joystick2.v);
			transform.LookAt(targetDir + transform.position);
			cc.SimpleMove(transform.forward * speed);
		}
		
		//targetDir.Set(h, 0, v);
		//playerRigidbody.MovePosition(transform.position + targetDir.normalized * speed * Time.deltaTime);
    }

    void Animating(float h, float v)
    {
        if (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)
        {
            anim.SetBool("Walk", true);
        }
        else
        {
            anim.SetBool("Walk", false);
        }
    }
}
